<template>
  <el-dialog
    v-el-drag-dialog
    title="盘点详情"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        <el-button type="primary" icon="el-icon-download" :loading="$loadingPlugin.exportFile" @click="exportFile">导出</el-button>
      </div>
      <div>
        <el-select v-model="mode" style="width: 150px;" @change="modeChange">
          <el-option :value="1" label="配送员视角" />
          <el-option :value="2" label="客户视角" />
        </el-select>
      </div>
    </div>
    <el-form ref="dataForm" class="form" :model="temp" label-position="right" label-width="80px">
      <el-form-item v-show="mode === 2" label="名称" prop="csmName">
        <el-input v-model.trim="temp.csmName" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item v-show="mode === 2" label="电话" prop="csmPhone">
        <el-input v-model.trim="temp.csmPhone" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item v-show="mode === 2" label="地址" prop="csmAddress">
        <el-input v-model.trim="temp.csmAddress" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="盘点机构:" prop="orgId">
        <el-tree-select
          v-model="temp.orgId"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
      </el-form-item>
      <el-form-item label="盘点人:" prop="userId">
        <el-select v-model="temp.userId" :loading="$loadingPlugin.getOwnersList" style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      @fetch="fetchData"
    />
  </el-dialog>
</template>

<script>
  import { queryInventoryPlanDetailTableList, queryInventoryPlanDetail, queryInventoryCheckUserList, queryInventPlanDetailTableHeader } from '@/api'
  import { mapGetters } from 'vuex'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'

  export default {
    name: 'add',
    data() {
      return {
        visible: false,
        treeData: [],
        mode: 1,
        ownersList: [],
        temp: {
          orgId: '',
          userId: '',
          csmName: '',
          csmPhone: '',
          csmAddress: ''
        },
        tableData: {
          total: 0,
          column: [],
          column1: [
            {
              prop: 'orgName',
              label: '盘点机构',
              width: 200
            },
            {
              prop: 'userName',
              label: '盘点人',
              width: 100
            }
          ],
          column2: [
            {
              prop: 'csmName',
              label: '客户名称',
              width: 100
            },
            {
              prop: 'csmPhone',
              label: '客户电话',
              width: 110
            },
            {
              prop: 'csmAddress',
              label: '客户地址'
            },
            {
              prop: 'addressOrgName',
              label: '归属机构'
            },
            {
              prop: 'userName',
              label: '盘点人',
              width: 80
            }
          ],
          data: []
        },
        fileList: [],
        initSelectDateTotal: false // 是否需要查询数据汇总
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ]),
      column: function() {
        if (this.mode === 1) return this.tableData.column1
        else return this.tableData.column2
      }
    },
    created() {
      this.getTreeData()
      this.initTableHeader()
    },
    methods: {
      open(temp) {
        this.getDetailData(temp.planCode)
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
          }
        })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          tabPage: this.mode,
          planCode: this.temp.planCode,
          currentPage,
          pageSize
        }
        if (this.mode === 1) { // 配送员视角
          if (this.temp.orgId) query.orgId = this.temp.orgId
          if (this.temp.userId) query.userId = this.temp.userId
        } else {
          query.csmName = this.temp.csmName
          query.csmPhone = this.temp.csmPhone
          query.csmAddress = this.temp.csmAddress
          if (this.temp.orgId) query.addressOrgId = this.temp.orgId
        }
        if (!query.orgId) query.orgId = -1
        const res = await queryInventoryPlanDetailTableList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      async initTableHeader() {
        const res = await queryInventPlanDetailTableHeader({
          planCode: this.temp.planCode
        })
        if (res.data.length > 0) {
          // 配送员模式
          let cls = []
          if (this.mode === 1) {
            cls = [
              { label: '盘点机构', prop: 'orgName', width: 200 },
              { label: '盘点人', prop: 'userName', width: 100 }
            ]
            // 客户模式
          } else if (this.mode === 2) {
            cls = [
              { label: '客户名称', prop: 'csmName', width: 100 },
              { label: '客户电话', prop: 'csmPhone', width: 100 },
              { label: '客户地址', prop: 'csmAddress', width: 200 },
              { label: '归属机构', prop: 'addressOrgName', width: 200 },
              { label: '盘点人', prop: 'userName', width: 100 }
            ]
          }
          var columns = [
            { label: '小计', prop: 'total', width: 90, align: 'right', formatter: this.totalFormat }]
          for (let x = 0; x < res.data.length; x++) {
            var bean = res.data[x]
            var fileBean = {}
            fileBean.ggxh = bean.ggxh
            this.fileList.push(fileBean)
            columns.unshift({ label: bean.typeName, prop: bean.ggxh, width: 100 })
          }
          for (let y = 0; y < columns.length; y++) {
            cls.push(columns[y])
          }
          this.tableData.column = cls
          // 需要查询数据
          this.initSelectDateTotal = true
        } else {
          // 配送员模式
          let cls = []
          if (this.mode === 1) {
            cls = [
              { label: '盘点机构', prop: 'orgName', width: 200 },
              { label: '盘点人', prop: 'userName', width: 100 }
            ]
            // 客户模式
          } else if (this.mode === 2) {
            cls = [
              { label: '客户名称', prop: 'csmName', width: 100 },
              { label: '客户电话', prop: 'csmPhone', width: 100 },
              { label: '客户地址', prop: 'csmAddress', width: 200 },
              { label: '归属机构', prop: 'addressOrgName', width: 200 },
              { label: '盘点人', prop: 'userName', width: 100 }
            ]
          }
          this.tableData.column = cls
          // 不需要查询数据
          this.initSelectDateTotal = false
        }
      },
      async getDetailData(planCode) {
        const res = await queryInventoryPlanDetail({ planCode })
        this.temp = res.data
        this.temp.orgIds = res.data.checkPlanOrgList.map(item => item.orgId)
        this.temp.date = [moment(res.data.startTime), moment(res.data.endTime)]
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.getOwnersList(value.orgId)
        this.$set(this.temp, 'userId', '')
      },
      // 查询盘点人列表
      async getOwnersList(orgId) {
        const res = await queryInventoryCheckUserList({
          orgId,
          planCode: this.temp.planCode
        })
        this.ownersList = res.data
      },
      closeTree(v) {
        this.$set(this.temp, 'userId', '')
        this.ownersList = []
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const params = {
            startTime: moment(this.temp.date[0]).format(),
            endTime: moment(this.temp.date[1]).format(),
            orgIds: this.temp.orgIds.join(','),
            remark: this.temp.remark
          }
          if (this.type === 'edit') params.planCode = this.temp.planCode
          if (this.type === 'add') {
            this.add(params)
          } else {
            this.edit(params)
          }
        })
      },
      totalFormat(row) {
        if (!row.total || row.total === 0) {
          return 0
        }
        return row.total
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      reset() {
        this.type = 'add'
        this.temp = {
          date: [],
          orgIds: [],
          remark: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
